package com.huan.atm;

import java.util.ArrayList;
import java.util.List;

public class Bank {
    private List<BankAccount> accounts = new ArrayList<>();
    public Bank() {
        //初始化账号
        for (int i=1;i<=10;i++){
            accounts.add(new BankAccount(i,10));
        }
    }

    //查询余额
    public BankAccount queryBalance(int id){
        for (BankAccount b:accounts){
            if (b.getId()==id)
                return b;
        }
        throw new RuntimeException("账号"+id+"不存在");
    }

    //存款:需加锁
    public BankAccount deposit(int id,double money){
        BankAccount b = queryBalance(id);
        synchronized (b){
            b.setBalance(b.getBalance()+money);
        }
        return b;
    }

    //取款
    public BankAccount withdraw(int id,double money){
        BankAccount b = queryBalance(id);
        synchronized (b){
            if (b.getBalance()<money)
                throw new RuntimeException("余额不足");
            b.setBalance(b.getBalance()-money);
        }
        return b;
    }
}
